package com.dayu.finecomm.dsc.net;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayu.finecomm.dsc.DSCInterface;
import com.dayu.finecomm.dsc.handler.DSCTcpListen;

/**
 * 创建Tcp Listen Socket
 * @author hddz
 * @since 2017-07-26 15:28:30
 * @version V1.0
 *
 */
public class DSCTcpServer extends DSCSocketServer {
	static Logger LOGGER = LoggerFactory.getLogger(DSCTcpServer.class);
	
	/**
	 * 线程EventLoopGroup
	 */
	EventLoopGroup mBoss = null;		// boss线程
	EventLoopGroup mWorkers = null;		// worker线程
	
	public DSCTcpServer(String strHost, int nPort, DSCInterface callback) {
		if (null != strHost) {
			mHost = new String(strHost);
		}
		
		mPort = nPort;
		
		mCallback = callback;
	}
	
	/**
	 * 启动监听TCP Socket
	 * @return ChannelFuture
	 * @throws InterruptedException
	 */
	@Override
	public ChannelFuture bootstrap() throws InterruptedException {
		mBoss = new NioEventLoopGroup();
		mWorkers = new NioEventLoopGroup();

		ServerBootstrap b = new ServerBootstrap();

		b.channel(NioServerSocketChannel.class);
		b.group(mBoss, mWorkers);
		b.childHandler(new DSCTcpListen(this));
		b.option(ChannelOption.SO_KEEPALIVE, true);

		ChannelFuture f = null;
		if (null == mHost || true == mHost.isEmpty()) {
			f = b.bind(mPort).sync();
		} else {
			f = b.bind(mHost, mPort).sync();
		}

		ChannelFuture cf = f.channel().closeFuture();

		cf.addListener(new GenericFutureListener<Future<? super Void>>() {

			@Override
			public void operationComplete(Future<? super Void> future)
					throws Exception {
				mBoss.shutdownGracefully();
				mWorkers.shutdownGracefully();
			}
		});

		return cf;
	}
	
	/**
	 * 退出
	 */
	@Override
	public void shutdown() {
		if (null != mBoss) {
			mBoss.shutdownGracefully();
			mBoss = null;
		}
		
		if (null != mWorkers) {
			mWorkers.shutdownGracefully();
			mWorkers = null;
		}
	}
}
